#include <fstream> 	// file stream
#include <iostream>	// io stream
#include <string>	
#include <stdlib.h>
#include <time.h> 
using namespace std;
#define MAX 400
int main() 
{

	ifstream inFile; 
	inFile.open("data1.txt"); // open file

	double* x1 = new double[MAX];
	double* x2 = new double[MAX];
	double* x3 = new double[MAX];
	double* x4 = new double[MAX];
	double*	y0 = new double[MAX];
	int n1, n2, n3, n4, k;
	n1 = n2 = n3 = n4 = k = 0;

	if(inFile.is_open()){
		
		cout << "Reading..." << endl;

		while(!inFile.eof()){ 
			
			inFile >> x1[n1++];
			// cout << x1[n1++] << " ";

			inFile >> x2[n2++];
			// cout << x2[n2++] << " ";

			inFile >> x3[n3++];
			// cout << x3[n3++] << " ";

			inFile >> x4[n4++];
			// cout << x4[n4++] << " ";

			inFile >> y0[k++];
			// cout << y0[k++] << endl;

		} 
	} 
	
	inFile.close(); 

	// for(int i=0; i<20; i++)
	// {
	// 	cout << x1[i] << " ";
	// 	cout << x2[i] << " ";
	// 	cout << x3[i] << " ";
	// 	cout << x4[i] << " ";
	// 	cout << y0[i] << endl;
	// }

	int average = 0;
	double epsilon = 0.5;

	for(int t = 0; t < 2000; t++)
	{
		double w0, w1, w2, w3, w4;
		w0 = w1 = w2 = w3 = w4 = 0;

		int total_update = 0;

		while(1) // halts until no more mistakes
		{

			// random input data order
			srand((unsigned) time(NULL));
			int t = MAX;
			while(t--)
			{
				int index = rand() % MAX;
				double temp;
				temp = x1[index];
				x1[index] = x1[0];
				x1[0] = temp;

				temp = x2[index];
				x2[index] = x2[0];
				x2[0] = temp;

				temp = x3[index];
				x3[index] = x3[0];
				x3[0] = temp;

				temp = x4[index];
				x4[index] = x4[0];
				x4[0] = temp;

				temp = y0[index];
				y0[index] = y0[0];
				y0[0] = temp;
			}

			int n = 0;

			for(int i= 0;i<MAX;i++) // one cycle
			{
				double temp = w0 + w1 * x1[i] + w2 * x2[i] + w3 * x3[i] + w4 * x4[i]; // w(t) * x(n)
				double s = y0[i];

				if(temp == 0) temp = -1;
				
				// cout << " w(t)*x(n) = " << temp << endl;
				// cout << " y(n) = " << s << endl;
				// cout << "w0 = "<< w0 <<" w1 = " << w1 << " w2 = " << w2 << " w3 = " << w3 << " w4 = " << w4 << endl;
				// cout << "x1 = " << x1[i] << " x2 = " << x2[i] << " x3 = " << x3[i] << " x4 = " << x4[i] << endl;
				// system("pause");

				if( temp*s > 0  ) // approve: sign(w(t) * x(n) > threshold
				{
					continue;
					//flag = false;
				}
				else // deny: sign(w(t) * x(n)) < threshold
				{
					// w(t+1) = w(t) + y(n)*x(n)
					w0 += s*epsilon;
					w1 += s * x1[i]*epsilon;
					w2 += s * x2[i]*epsilon;
					w3 += s * x3[i]*epsilon;
					w4 += s * x4[i]*epsilon;
					total_update++;
					n++;
				}
			}
			if(n==0) break;
		}

		cout << "w0 = "<< w0 <<" w1 = " << w1 << " w2 = " << w2 << " w3 = " << w3 << " w4 = " << w4 << endl;

		average += total_update;
	}

	cout << "total average is " << average/2000 << endl;

	system("pause");

	return 1;
} 